﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Magicodes.ExporterAndImporter.Core;
using Magicodes.ExporterAndImporter.Core.Models;
using Magicodes.ExporterAndImporter.Excel;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.VisualBasic;
using Paas.Pioneer.Domain.Shared.Configs;
using Paas.Pioneer.Domain.Shared.Helpers;
using Paas.Pioneer.Excel.Application.Contracts.Excel.Dto;
using Volo.Abp.AspNetCore.Mvc;

namespace Paas.Pioneer.Excel.HttpApi.Controllers;

[Route("api/[controller]")]
public class ExcelController : AbpController
{
    private readonly UploadConfig _uploadConfig;
    private readonly UploadHelper _uploadHelper;
    private readonly IExcelImporter _excelImporter;
    private readonly IExcelExporter _excelExporter;

    public ExcelController(
        IOptionsMonitor<UploadConfig> uploadConfig,
        IOptionsMonitor<UploadHelper> uploadHelper, IExcelImporter excelImporter, IExcelExporter excelExporter)
    {
        this._excelImporter = excelImporter;
        _uploadConfig = uploadConfig.CurrentValue;
        _uploadHelper = uploadHelper.CurrentValue;
        _excelExporter = excelExporter;
    }

    [HttpPost]
    public async Task ExcelAsync(IFormFile file)
    {
        Console.WriteLine($"开始加载数据，准备加载数据{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}");
        var fileStream = file.OpenReadStream();
        var sheetDic = await _excelImporter.ImportMultipleSheet<ExcelDto>(fileStream);
        Console.WriteLine($"数据加载完毕，准备处理数据{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}");
        List<Task> list = new List<Task>();
        var networkCardList = sheetDic["网卡信息"].Data;
        List<NetworkCardShouZhiDto> networkCardShouZhiDtoList = new List<NetworkCardShouZhiDto>(networkCardList.Count);
        networkCardShouZhiDtoList.AddRange(networkCardList.Select(x =>
        {
            var networkCardDto = x as NetworkCardDto;
            return new NetworkCardShouZhiDto
            {
                ActivationTime = networkCardDto.ActivationTime,
                IMEI = networkCardDto.IMEI,
                CardStatus = networkCardDto.CardStatus,
                BasicPackage = networkCardDto.BasicPackage,
                CardType = networkCardDto.CardType,
                VirtualNo = networkCardDto.VirtualNo,
                CarrierName = networkCardDto.CarrierName,
                WalletBalance = networkCardDto.WalletBalance,
                Number = networkCardDto.Number,
                PhoneNumber = networkCardDto.PhoneNumber,
                ICCID = networkCardDto.ICCID,
                SubscriberNumber = networkCardDto.SubscriberNumber,
                Developer = networkCardDto.Developer,
                ExpirationTime = networkCardDto.ExpirationTime,
                NameDistributor = networkCardDto.NameDistributor,
                CurrentPackage = networkCardDto.CurrentPackage,
                LevelAgents = networkCardDto.LevelAgents,
            };
        }));

        foreach (var item in sheetDic)
        {
            if (item.Key == "网卡信息")
            {
                continue;
            }

            list.Add(Task.Run(() =>
            {
                var import = item.Value;
                var month = int.Parse(item.Key.Replace("月份收入", "").Replace("月份支出", "").Trim());
                if (import.Data == null)
                {
                    return;
                }
                foreach (NetworkCardShouZhiDto networkItem in networkCardShouZhiDtoList)
                {
                    if (item.Key.EndsWith("支出"))
                    {
                        var zhichuList = import.Data.Select(x => x as ExpenditureDto);
                        var zhichu = zhichuList.FirstOrDefault(x => x.ICCID == networkItem.ICCID);
                        if (zhichu == null)
                        {
                            continue;
                        }
                        decimal.TryParse(zhichu.TotalflowGB, out decimal totalflowGB);
                        if (month == 1)
                        {
                            networkItem.JanuaryTotalFlow = totalflowGB;
                            networkItem.JanuaryExpenditure = zhichu.DiscountedCost;
                        }
                        else if (month == 2)
                        {
                            networkItem.FebruaryTotalFlow = totalflowGB;
                            networkItem.FebruaryExpenditure = zhichu.DiscountedCost;
                        }
                        else if (month == 3)
                        {
                            networkItem.MarchTotalFlow = totalflowGB;
                            networkItem.MarchExpenditure = zhichu.DiscountedCost;
                        }
                        else if (month == 4)
                        {
                            networkItem.AprilTotalFlow = totalflowGB;
                            networkItem.AprilExpenditure = zhichu.DiscountedCost;
                        }
                        else if (month == 5)
                        {
                            networkItem.MayTotalFlow = totalflowGB;
                            networkItem.MayExpenditure = zhichu.DiscountedCost;
                        }
                        else if (month == 6)
                        {
                            networkItem.JuneTotalFlow = totalflowGB;
                            networkItem.JuneExpenditure = zhichu.DiscountedCost;
                        }
                        else if (month == 7)
                        {
                            networkItem.JulyTotalFlow = totalflowGB;
                            networkItem.JulyExpenditure = zhichu.DiscountedCost;
                        }
                        else if (month == 8)
                        {
                            networkItem.AugustTotalFlow = totalflowGB;
                            networkItem.AugustExpenditure = zhichu.DiscountedCost;
                        }
                        else if (month == 9)
                        {
                            networkItem.SeptemberTotalFlow = totalflowGB;
                            networkItem.SeptemberExpenditure = zhichu.DiscountedCost;
                        }
                        else if (month == 10)
                        {
                            networkItem.OctoberTotalFlow = totalflowGB;
                            networkItem.OctoberExpenditure = zhichu.DiscountedCost;
                        }
                        else if (month == 11)
                        {
                            networkItem.NovemberTotalFlow = totalflowGB;
                            networkItem.NovemberExpenditure = zhichu.DiscountedCost;
                        }
                        else if (month == 12)
                        {
                            networkItem.DecemberTotalFlow = totalflowGB;
                            networkItem.DecemberExpenditure = zhichu.DiscountedCost;
                        }
                    }
                    else if (item.Key.EndsWith("收入"))
                    {
                        var shouruList = import.Data.Select(x => x as IncomeDto);
                        if (shouruList.All(x => x.ICCID != networkItem.ICCID))
                        {
                            continue;
                        }

                        var shouru = shouruList.Where(x => x.ICCID == networkItem.ICCID).Select(x =>
                        {
                            return x.PlaceOrderAmount / x.Count;
                        }).Sum();
                        if (month == 1)
                        {
                            networkItem.JanuaryIncome = shouru;
                        }
                        else if (month == 2)
                        {
                            networkItem.FebruaryIncome = shouru;
                        }
                        else if (month == 3)
                        {
                            networkItem.MarchIncome = shouru;
                        }
                        else if (month == 4)
                        {
                            networkItem.AprilIncome = shouru;
                        }
                        else if (month == 5)
                        {
                            networkItem.MayIncome = shouru;
                        }
                        else if (month == 6)
                        {
                            networkItem.JuneIncome = shouru;
                        }
                        else if (month == 7)
                        {
                            networkItem.JulyIncome = shouru;
                        }
                        else if (month == 8)
                        {
                            networkItem.AugustIncome = shouru;
                        }
                        else if (month == 9)
                        {
                            networkItem.SeptemberIncome = shouru;
                        }
                        else if (month == 10)
                        {
                            networkItem.OctoberIncome = shouru;
                        }
                        else if (month == 11)
                        {
                            networkItem.NovemberIncome = shouru;
                        }
                        else if (month == 12)
                        {
                            networkItem.DecemberIncome = shouru;
                        }
                    }
                }
            }));
        }
        Task.WaitAll(list.ToArray());
        Console.WriteLine($"数据处理完毕,开始生成数据{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}");
        var result = await _excelExporter.Export($"流量费计算模板{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx", networkCardShouZhiDtoList);
        Console.WriteLine($"生成完毕{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}");
    }
}